#ifndef __USB_COMMUNICATION_H__
#define __USB_COMMUNICATION_H__

#include "libusb.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <thread>
#include <wx/event.h>
// #include <wx/thread.h>


// // 定义自定义事件类
// class USBCommunicationEvent : public wxCommandEvent {
// public:
//     USBCommunicationEvent(wxEventType eventType = wxEVT_NULL,int id = 0)
//         : wxCommandEvent(eventType, id) {

//         }

//     // 克隆事件对象
//     [[nodiscard]] // C++17 才支持，意思就是函数返回值不能被忽略，否则编译器发出警告
//     virtual wxEvent *Clone() const override {
//         return new USBCommunicationEvent(*this);
//     }


// private:

// };

// wxDECLARE_EVENT(mEVT_USBCOMMON, USBCommunicationEvent);

class USBCommunication
{
public:
    typedef enum
    {
        SUCCESS = 0,
        TIMEOUT,
        FAIL
    }Status;

public:
    USBCommunication(uint16_t _vid = 0x0000, uint16_t _pid = 0x0000,int infNum = 0);
    ~USBCommunication();

    void SetVidPid(uint16_t _vid, uint16_t _pid);
    void SetInterfaceNumber(int infNum);
    bool Connect();
    bool Disconnect();
    bool IsConnected();
    bool StartHotplugCheck();
    Status WriteData(const char *data, int len, unsigned char endpoint, int timeout);
    Status ReadData(char *data, int length, int *actual_length,unsigned char endpoint,int timeout);

private:
    libusb_context *usb_contex;
    libusb_device_handle *hDevice = nullptr;
    libusb_hotplug_callback_handle device_hotplug_handle;
    bool isConnected = false;
    uint16_t vid = 0x0000;
    uint16_t pid = 0x0000;
    int kernelDriverDetached = false;
    int interface_number;
    std::thread thread_libusb;
    bool isRunning;

    static int LIBUSB_CALL device_hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, libusb_hotplug_event event, void *userdata);
    static void LIBUSB_CALL myLibusbLog(libusb_context *contex,enum libusb_log_level level,const char *msg);
    void thread_run(void *parm);
};


// typedef void (wxEvtHandler::*MyCommandEventFunction)(USBCommunicationEvent &);

// #define MyCommandEventHandler(func) \
//     wxEVENT_HANDLER_CAST(MyCommandEventFunction, func)

// #define MY_EVT_EQUALIZER(id, fn) \
//     wx__DECLARE_EVT1(mEVT_USBCOMMON, id, MyCommandEventHandler(fn))


#endif
